package com.example.jetpacklearn

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.jetpacklearn.liftcycle.LiveDataMusic

/**
 *
 * @ClassName:      PlayerPresenter$
 * @Description:    java类作用描述
 * @Author:         xinya
 * @CreateDate:     2020/11/1$ 12:23$
 * @UpdateRemark:   更新内容
 * @Version:        1.0
 *
 *
 * 相关数据
 *      当前播放的歌曲
 *      当前播放的状态
 */
class PlayerPresenter private constructor() {

    private val callbackList = arrayListOf<IPlayerCallback>()
    enum class PlayStatus {
        NONE, PLAYING, PAUSE, LOADING
    }
    private val playerAPI by lazy {
        PlayerAPI()
    }
    var playStatus = DataListenerContainer<PlayStatus>()
    var currentMusic = DataListenerContainer<MusicBean>()
    var currentLifeMusic = MutableLiveData<MusicBean>()
    var liveDataMusic = LiveDataMusic.instance

    private var currentMusicIndex = 0
    private val playerSDK by lazy {
        PlayerSDK.instance
    }

    init {
        playStatus.value = PlayStatus.NONE
    }

    companion object {
        private const val TAG = "PlayerPresenter"
        val instance by lazy {
            PlayerPresenter()
        }
    }

    fun registerCallback(callback: IPlayerCallback) {
        if (!callbackList.contains(callback)) {
            callbackList.add(callback)
        }
    }

    fun unregisterCallback(callback: IPlayerCallback) {
        callbackList.remove(callback)
    }

    /**
     * 下一首
     */
    fun doPlayNext() {
        currentMusic.value = playerAPI.getMusicById(++currentMusicIndex)
        currentLifeMusic.postValue(playerAPI.getMusicById(currentMusicIndex))
        liveDataMusic.postValue(playerAPI.getMusicById(currentMusicIndex))
    }

    /**
     * 暂停或播放
     */
    fun doPlayOrPause() {
        if (currentMusic.value == null) {
            currentMusic.value = playerAPI.getMusicById(currentMusicIndex)
            currentLifeMusic.postValue(playerAPI.getMusicById(currentMusicIndex))
            liveDataMusic.postValue(playerAPI.getMusicById(currentMusicIndex))
        }

        playStatus.value = when (playStatus.value) {
            PlayStatus.PLAYING -> {
                Log.d(TAG, "doPlayOrPause: PLAYING")
                playerSDK.pause()
                PlayStatus.PAUSE
            }
            else -> {
                Log.d(TAG, "doPlayOrPause: else")
                playerSDK.play(currentMusic.value)
                PlayStatus.PLAYING
            }
        }
    }

    /**
     * 上一首
     */
    fun doPlayPrevious() {
        currentMusic.value = playerAPI.getMusicById(--currentMusicIndex)
        currentLifeMusic.postValue(playerAPI.getMusicById(currentMusicIndex))
        liveDataMusic.postValue(playerAPI.getMusicById(currentMusicIndex))
    }


    /**
     * ====控制====
     * 播放音乐
     * 暂停音乐
     * 上一首
     * 下一首
     *
     * ====播放状态====
     * 通知UI改变播放状态
     * 通知UI进度的变化
     * 上一首
     * 下一首
     * 通知UI歌曲标题改变
     * 通知UI歌曲封面的改变
     * 暂停音乐
     *
     */
}